export command
export
- Set export attribute for shell variables.
The export
command in Linux is a shell built-in used to set environment variables and make them available to child processes (like scripts or new terminal sessions). Environment variables store information (e.g., paths, settings) that programs can access.
Usage: export [-fn] [name[=value] ...]
name
: The variable name to set or export.value
: The value assigned to the variable (optional).- No standalone executable; it’s built into shells like bash.
Examples
-
Basic Usage
Set a variable and export it to make it available to subprocesses.
export MYVAR="Hello"
- Sets
MYVAR
to "Hello" and exports it. - Child processes (e.g., scripts) can now access
MYVAR
.
Verify:
echo $MYVAR
- Output:
Hello
- Sets
-
Checking Exported Variables
Use
export
without arguments to list all exported variables.export
- Output: A list like
declare -x MYVAR="Hello"
, showing all exported variables and their values.
Alternative:
printenv
- Lists only environment variables (similar to
export
output).
- Output: A list like
-
Exporting an Existing Variable
If a variable is already set,
export
makes it available to child processes.NAME="Alice"
echo $NAME # Works in current shell
bash -c 'echo $NAME' # Empty, not exported yet
export NAME
bash -c 'echo $NAME' # Now outputs "Alice"
Typing `export NAME`Alice- Before
export
,NAME
isn’t available in the subprocess (bash -c
). - After
export
, it’s accessible.
- Before
-
Temporary Export
Variables exported in a session last only until the terminal closes.
export TEMP="Temporary"
TEMP
is available until you exit the shell.- To make it permanent, add it to a file like
~/.bashrc
(see below).
-
Permanent Export
Add
export
commands to shell configuration files (e.g.,~/.bashrc
or~/.bash_profile
) for persistence.Edit
~/.bashrc
:echo 'export MY_PATH="/usr/local/bin"' >> ~/.bashrc
source ~/.bashrcMY_PATH
is now set every time you start a new shell.
-
Using with Paths
Commonly used to modify the
PATH
variable for executable locations.export PATH="$PATH:/home/user/scripts"
- Adds
/home/user/scripts
to the search path for commands. - Verify:
echo $PATH
.
- Adds
To get help related to the export
command use --help
option
$ export --help
export: export [-fn] [name[=value] ...] or export -p
Set export attribute for shell variables.
Marks each NAME for automatic export to the environment of subsequently
executed commands. If VALUE is supplied, assign VALUE before exporting.
Options:
-f refer to shell functions
-n remove the export property from each NAME
-p display a list of all exported variables and functions
An argument of `--' disables further option processing.
Exit Status:
Returns success unless an invalid option is given or NAME is invalid.